import { ComponentClass } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image, Text, Picker } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import { AtForm, AtInput, AtInputNumber, AtButton, AtIcon, AtToast, AtTextarea, AtList, AtListItem, AtActionSheet, AtActionSheetItem } from 'taro-ui'

import { prefix, image_prefix } from '../../utils'

import { add } from '../../actions/goods'

import './index.scss'

type PageStateProps = {
  goods: object | {},
}

type PageDispatchProps = {
  add: () => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Activity {
  props: IProps
}

@connect(({ goods }) => ({
  goods
}), (dispatch) => ({
  add(data, callback) {
    dispatch(add(data, callback))
  }
}))
class Activity extends Component {
  config: Config = {
    navigationBarTitleText: '幸运草小程序'
  }

  state = {
    title: '',
    explain: '',
    date: '请选择开奖日期',
    time: '请选择开奖时间',
    isOpened: false,
    isToastOpened: false,
    data: {
      GoodsPrizes: [
        {
          number: 1,
          cover: ''
        }
      ],
      brief: '',
      style: -1,
      number: 0,
      date: '',
      time: ''
    }
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props, nextProps)
  }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }

  handleAddComponent = () => {
    this.setState(state => ({
      ...state,
      isToastOpened: true,
    }))
  }

  handleImageUpload = () => {
    Taro.getSetting().then(e=>{
      if(e.authSetting['scope.userInfo']) {
        
        Taro.chooseImage({
          count: 1,
          sizeType: 'compressed'
        }).then(results => {
          const { tempFilePaths = [] } = results
          Taro.uploadFile({
            url: `${prefix}/api/v1/uploads`,
            filePath: tempFilePaths[0],
            name: 'file',
          }).then(results => {
            const data = JSON.parse(results.data)
            Taro.showToast({ title: `奖品图片上传成功~`, icon: 'success' })
            this.setState(state => ({
              ...state,
              data: {
                ...state.data,
                GoodsPrizes: [{...state.data.GoodsPrizes[0], cover: data.data.name }],
              }
            }), () => console.log(this.state, 'state'))
          })
        }).catch(() => Taro.showToast({ title: `图片上传失败`, icon: 'none' }))      
        
      } else {
        Taro.showToast({ title: `请先登录！`, icon: 'none' })
      }
    })

  }


  handleSubmits = () => {

    Taro.getSetting().then(e=>{
      if(e.authSetting['scope.userInfo']) {
        const { GoodsPrizes, number, nickname, brief, userId, style, date, time  } = this.state.data
        const { title, cover } = GoodsPrizes[0]
        if(style === -1) return Taro.showToast({ title: `请选择开奖条件！`, icon: 'none' })
        if(!date && !number) return Taro.showToast({ title: `按人数或按日期时间开奖至少选填一项！`, icon: 'none' })
        if(!title) return Taro.showToast({ title: `奖品名称不能为空！`, icon: 'none' })
        if(!cover) return Taro.showToast({ title: `奖品图片不能为空！`, icon: 'none' })

        const obj = {}
        if(date && time) Object.assign(obj, {endAt: date + ' ' + time})

        // console.log({...this.state.data, ...obj}, '123321')
        this.props.add({...this.state.data, ...obj}, (data) => {
          if(data.errno) {
            Taro.showToast({ title: data.errmsg, icon: 'none' })
          } else {
            Taro.showToast({ title: `奖品添加成功~`, icon: 'success' })            
          }
        })
      } else {
        Taro.showToast({ title: `请先登录！`, icon: 'none' })
      }
    })


  }

  handleInputChange = title => {
    this.setState(state => ({
      ...state,
      data: {
        ...state.data,
        GoodsPrizes: [{ ...state.data.GoodsPrizes[0], title }]
      }
    }), () => console.log(this.state, '123'))
  }

  handleNumberChange = number => {
    this.setState(state => ({
      ...state,
      data: {
        ...state.data,
        GoodsPrizes: [{ ...state.data.GoodsPrizes[0], number }]
      }
    }), () => console.log(this.state, '123'))
  }

  handleTextareaChange = e => {
    e.stopPropagation()
    const value = e.target.value
    this.setState(state => ({
      ...state,
      data: {
        ...state.data,
        brief: value
      }
    }), () => console.log(this.state, '123'))
  }

  handleActionSheetSelect = e => {
    e.stopPropagation()
    this.setState(state => ({
      ...state,
      isOpened: true,
    }))
  }

  handleDateTimeChange = (flag, e) => {
    e.stopPropagation()

    const value = e.target.value
    let data: object = {}
    if (flag === 1) data = { date: value }
    if (flag === 0) data = { time: value }
    this.setState(state => ({
      ...state,
      data: {
        ...state.data,
        ...data,
      },
      isOpened: false,
    }), () => console.log(this.state, '123'))
  }

  handleStyleChange = (style, e) => {
    e.stopPropagation()
    this.setState(state => ({
      ...state,
      isOpened: false,
      data: {
        ...state.data,
        style
      }
    }), () => console.log(this.state, 123))
  }

  handleStyleNumberChange = (number, e) => {
    e.stopPropagation()
    // replace(/[^0-9]/ig,"");
    this.setState(state => ({
      ...state,
      isOpened: false,
      data: {
        ...state.data,
        number
      }
    }), () => console.log(this.state, 123))
  }

  render() {
    return (
      <View className='Goods'>
        <AtToast isOpened={this.state.isToastOpened} text='正在开发中...' />
        <View className='GoodsGroup'>
          <View className='GoodsImageUpload' onClick={this.handleImageUpload}>
            <Image 
              src={
                this.state.data.GoodsPrizes[0].cover 
                ? 
                image_prefix + this.state.data.GoodsPrizes[0].cover
                :
                'https://via.placeholder.com/350x150'
              } 
              mode='widthFix' 
              className='image' 
            />
          </View>
          <AtForm>
            <AtInput
              name='value1'
              title='奖品名称'
              type='text'
              placeholder='请输入奖品名称'
              value={this.state.title}
              onChange={this.handleInputChange}
            />
            <View className='GoodsInputNumber'>
              <View className='GoodsInputNumberLabel'>
                <Text className='text'>奖品数量</Text>
              </View>
              <AtInputNumber
                className='GoodsInputNumberValue'
                min={1}
                max={100}
                step={1}
                value={this.state.data.GoodsPrizes[0].number}
                onChange={this.handleNumberChange}
              />
            </View>
          </AtForm>
        </View>
        {/*<View className='GoodsButtonGroup'>
          <AtButton size='small' className='GoodsButtonButton' onClick={this.handleAddComponent}><AtIcon value='add' size='16' color='#ccc' />&nbsp;&nbsp;添加新奖品</AtButton>
        </View>*/}
        <View className='GoodsDivider'>
          <Text className='title'>抽奖说明</Text>
          <Text className='subtitle'>（抽奖说明）</Text>
        </View>
        <View className='GoodsTextarea'>
          <AtTextarea
            value={this.state.explain}
            onChange={this.handleTextareaChange}
            maxlength='200'
            placeholder='填写本次抽奖说明'
          />
        </View>
        <View className='GoodsDivider'>
          <Text className='title'>图文介绍</Text>
          <Text className='subtitle'>（非必填）</Text>
        </View>
        <AtList>
          <AtListItem
            title='开奖条件'
            arrow='right'
            extraText={this.state.data.style === 0 ? '按时间自动开奖' : this.state.data.style === 1 ? '按人数自动开奖' : '请选择开奖条件'}
            onClick={this.handleActionSheetSelect}
          />
          <AtActionSheet isOpened={this.state.isOpened} cancelText='取消'>
            <AtActionSheetItem onClick={this.handleStyleChange.bind(this, 0)}>
              按时间自动开奖
            </AtActionSheetItem>
            <AtActionSheetItem onClick={this.handleStyleChange.bind(this, 1)}>
              按人数自动开奖
            </AtActionSheetItem>
          </AtActionSheet>
          {
            this.state.data.style === 0
              ?
              <View>
                <Picker mode='date' range={this.state.date} onChange={this.handleDateTimeChange.bind(this, 1)}>
                  <AtListItem
                    title='开奖日期'
                    arrow='right'
                    extraText={this.state.data.date}
                  />
                </Picker>
                <Picker mode='time' range={this.state.time} onChange={this.handleDateTimeChange.bind(this, 0)}>
                  <AtListItem
                    title='开奖时间'
                    arrow='right'
                    extraText={this.state.data.time}
                  />
                </Picker>
              </View>
              :
              this.state.data.style === 1
                ?
                <AtForm style={{ marginTop: -1 }}>
                  <AtInput
                    name='number'
                    type='text'
                    placeholder='请输入按人数开奖的人数'
                    onChange={this.handleStyleNumberChange}
                  />
                </AtForm>
                :
                null
          }
        </AtList>
        <View className='GoodsButtonFixed'>
          <AtButton type='primary' onClick={this.handleSubmits}>发起抽奖</AtButton>
        </View>
      </View>
    )
  }
}

export default Activity as ComponentClass<PageOwnProps, PageState>